package marioarena.tcpconnection;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;


public class TCPSender extends Thread {
	private boolean connected;
	private DataOutputStream outputStream;
	private String tcpBuffer = "";
	
	/**
	 * Constructs a new TCPSender.
	 * @param socket The socket to be used for TCP.
	 */
	public TCPSender(Socket socket){
		try {
			outputStream = new DataOutputStream(socket.getOutputStream()); //Create stream
			this.start();
		} catch (IOException e) {e.printStackTrace();}
	}

	@Override
	public void run()
	{
		this.connected = true;
		while (connected)
		{
			try
			{
				// Lock the buffer string
				synchronized (tcpBuffer.intern())
				{
					if (!this.tcpBuffer.equals(""))
					{
						this.outputStream.writeBytes(this.tcpBuffer);
						outputStream.flush();
						tcpBuffer = ""; // Empty the buffer
					}
				}
				Thread.sleep(1);
			}
			catch (Exception e)
			{
				System.out.println("Buffer sending failed.");
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * Send a message using TCP. This message will be 
	 * buffered before sending.
	 * @param data The data to send using TCP.
	 */
	public void addToBuffer(String data)
	{
		synchronized (tcpBuffer.intern())
		{
			this.tcpBuffer += data + "\n";
		}
	}
	
	/**
	 * Disconnects the TCP sender.
	 */
	public void disconnect()
	{
		try {
			this.outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.connected = false;
	}
}
